package com.ikas.ai.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * HTML文本常用类
 * @author HXH
 */
public class HtmlUtil {

    private static Logger logger = LoggerFactory.getLogger(HtmlUtil.class);

    public static void main(String[] args) {
        String str = "<html><head><title>The page is temporarily unavailable</title><style>body { font-family: Tahoma, Verdana, Arial, sans-serif; }</style></head><body bgcolor=\"white\" text=\"black\"><table width=\"100%\" height=\"100%\"><tr><td align=\"center\" valign=\"middle\">The page you are looking for is temporarily unavailable.<br/>Please try again later.</td></tr></table></body></html>";
        logger.debug(getText(str));
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR, 17);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        logger.debug("{}", hour);
    }

    public static String getText(String html) {
        html = delHTMLTag(html);
        html = html.replaceAll("&nbsp;", "");
        return html;
    }

    /**
     * @param htmlStr
     * @return
     * 删除Html标签
     */
    private static String delHTMLTag(String htmlStr) {
        // 过滤script标签
        Pattern pscript = Pattern.compile(regExScript, Pattern.CASE_INSENSITIVE);
        Matcher mscript = pscript.matcher(htmlStr);
        htmlStr = mscript.replaceAll("");
        // 过滤style标签
        Pattern pstyle = Pattern.compile(regExStyle, Pattern.CASE_INSENSITIVE);
        Matcher mstyle = pstyle.matcher(htmlStr);
        htmlStr = mstyle.replaceAll("");
        // 过滤html标签
        Pattern phtml = Pattern.compile(regExHtml, Pattern.CASE_INSENSITIVE);
        Matcher mhtml = phtml.matcher(htmlStr);
        htmlStr = mhtml.replaceAll("");
        // 过滤空格回车标签
        // Pattern pspace = Pattern.compile(regExSpace, Pattern.CASE_INSENSITIVE);
        // Matcher mspace = pspace.matcher(htmlStr);
        // htmlStr = mspace.replaceAll("");
        // 返回文本字符串
        return htmlStr.trim();
    }

    /** 定义script的正则表达式 */
    private static String regExScript = "<script[^>]*?>[\\s\\S]*?<\\/script>";
    /** 定义style的正则表达式 */
    private static String regExStyle = "<style[^>]*?>[\\s\\S]*?<\\/style>";
    /** 定义HTML标签的正则表达式 */
    private static String regExHtml = "<[^>]+>";
    /** 定义空格回车换行符 */
    // private static final String regExSpace = "\\s*|\t|\r|\n";
}
